package cn.caplike.demo.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Description:
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2021-11-29 12:53
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) {
        final ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new HttpServerCodec()); // WebSocket 是基于 HTTP 的
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(8192)); // 对 HTTP 消息进行一个聚合
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); // ws://localhost:port/context-path | http 连接升级 (upgrade) 而成

        pipeline.addLast(new TextWebSocketFrameChannelInboundHandler());
    }

}
